﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Entities;
using System.ComponentModel;
using Cesave.Application.Permisos.ServiceAgent;
using System.Windows.Forms;

namespace Cesave.Presentation.Permisos.WinForms.Client.ViewModels.Permisos
{
	public partial class ExpedicionViewModel
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private List<Usuario> _usuarios;

		/// <summary>
		/// 
		/// </summary>
		private Usuario _usuario;

		#endregion

		#region Public properties

		/// <summary>
		/// 
		/// </summary>
		public List<Usuario> Usuarios
		{
			get
			{
				return _usuarios;
			}
			private set
			{
				_usuarios = value;
				if (_usuarios != null)
					RaisePropertyChanged("Usuarios");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public Usuario Usuario
		{
			get
			{
				return _usuario;
			}
			private set
			{
				_usuario = value;
				if (_usuario != null)
					RaisePropertyChanged("Usuario");
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public bool IsUsuarioReady
		{
			get
			{
				return Usuario != null;
			}
		}

		#endregion

		#region Private methods

		/// <summary>
		/// 
		/// </summary>
		private void LoadUsuarios()
		{
			StartWaiting();
			using (BackgroundWorker worker = new BackgroundWorker())
			{
				worker.DoWork += (sender, e) =>
				{
					using (PermisosModuleServiceWrapper service = new PermisosModuleServiceWrapper())
					{
						e.Result = service.FindUsuariosByJunta(_pusSettings.Junta.JuntaGuid);
					}
				};
				worker.RunWorkerCompleted += (sender, e) =>
				{
					EndWaiting();
					if (!e.Cancelled && e.Error == null)
						Usuarios = e.Result as List<Usuario>;
					else if (e.Error != null)
						ShowMessage(e.Error.Message);
				};
				worker.WorkerSupportsCancellation = true;
				worker.RunWorkerAsync();
			}
		}

		#endregion

		#region Event methods

		/// <summary>
		/// 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void SetCurrentUsuario(object sender, EventArgs e)
		{
			BindingSource bindingSource = sender as BindingSource;
			if (bindingSource != null && bindingSource.Current != null)
				Usuario = bindingSource.Current as Usuario;
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnUsuariosPropertyChanged()
		{
			_expedicionView.usuariosBindingSource.DataSource = Usuarios;
			_expedicionView.usuariosBindingSource.CurrentChanged += SetCurrentUsuario;
			SetCurrentUsuario(_expedicionView.usuariosBindingSource, new EventArgs());
		}

		/// <summary>
		/// 
		/// </summary>
		private void OnUsuarioPropertyChanged()
		{
            SetCurrentSeccion();
		}

		#endregion

	}
}
